package com.qf.cx.simplenms.webservice.controller;

import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qf.cx.simplenms.link.api.LinkStatus;
import com.qf.cx.simplenms.link.api.LinkStatus.State;
import com.qf.cx.simplenms.reader.api.ReaderManager;
import com.qf.cx.simplenms.readergroup.api.ReaderGroupManager;
import com.qf.cx.simplenms.subscriber.api.SubscriberManager;
import com.qf.cx.simplenms.tagmemory.api.TagMemoryManager;
import com.qf.cx.simplenms.topic.api.TopicManager;

@Controller
@RequestMapping(path = "/admin")
public class AdminController {

	@Autowired
	private ReaderManager readerManager;
	@Autowired
	private ReaderGroupManager readerGroupManager;
	@Autowired
	private TagMemoryManager tagMemoryManager;
	@Autowired
	private SubscriberManager subscriberManager;
	@Autowired
	private TopicManager topicManager;
	@Autowired
	private LinkStatus linkStatus;

	@RequestMapping(path = "/dump", method = RequestMethod.GET)
	@ResponseBody
	public String dump() {

		StringBuilder sb = new StringBuilder();
		sb.append(readerManager.dump());
		sb.append(readerGroupManager.dump());
		sb.append(tagMemoryManager.dump());
		sb.append(topicManager.dump());
		sb.append(subscriberManager.dump());
		return sb.toString();
	}

	@RequestMapping(path = "/link", method = RequestMethod.GET)
	@ResponseBody
	public String link() {
		Map<String, State> s = linkStatus.getLinkStatus();
		Map<String, State> ordered = new TreeMap<>(s);
		StringBuilder sb = new StringBuilder();
		sb.append("<table>");
		for (Entry<String, State> e : ordered.entrySet()) {
			sb.append("<tr>");
			sb.append("<td>" + e.getKey() + "</td>");
			sb.append("<td>" + e.getValue() + "</td>");
			sb.append("</tr>");
		}
		sb.append("</table>");
		return sb.toString();
	}
}